<template>
  <el-drawer size="900" v-model="_isOpen" modal-class="paymen-plan-drawer">
    <template #header>
      <p class="title">
        <i class="icon"></i>设置分期收款计划 <span>（设置后立即生效，对已结单的不影响，请根据业务需求设置）</span>
      </p>
    </template>
    <div class="content">
      <div class="info">
        <p class="f18" style="color: #3d3d3d">选中供应商数量：{{ _editArr.length }}</p>
        <div class="select-wrap">
          <div class="select-item" v-for="(item, index) in _editArr" :key="index">
            <p class="text-over" :title="item.factoryName || '-'">{{ item.factoryName || "-" }}</p>
            <el-icon v-if="_editArr.length > 1" style="color: #ff3333" @click="delFactory(item)"><CircleCloseFilled /></el-icon>
          </div>
        </div>
      </div>

      <div class="title" style="display: flex; justify-content: space-between">
        <p>收款关联节点</p>
        <el-button type="primary" link @click="addNode">
          <el-icon class="mr8"><CirclePlusFilled /></el-icon>新增付款节点
        </el-button>
      </div>

      <div class="list">
        <div class="list-item" v-for="(item, index) in list" :key="index">
          <header>
            <p>{{ index + 1 + "期款项" }}</p>
            <img src="@/assets/images/del.png" alt="" width="16px" @click="delNode(item, index)" />
          </header>
          <div class="options-warp">
            <div>
              <p class="label"><i style="color: #f53f3f">*</i><span>商家付款节点</span></p>
              <el-select
                v-model="item.businessNode"
                :style="{ width: '100%' }"
                placeholder="请选择"
                @change="getNodeList(item, index, $event, 1)"
              >
                <el-option
                  v-for="(_item, index) in item.businessNodeList"
                  :key="index"
                  :label="_item.dictLabel"
                  :value="_item.dictValue"
                >
                </el-option>
              </el-select>
              <el-input-number
                class="jzt-input-number jzt-input-number-hidden suffix"
                v-model="item.collectionScale"
                :min="0"
                :max="100"
                :style="{ width: '100%', marginLeft: '2px' }"
                placeholder="商家付款比例"
                controls-position="right"
                allow-clear
              >
              </el-input-number>
            </div>
            <div>
              <p class="label">供应商收款节点</p>
              <el-select
                v-model="item.collectionNode"
                :style="{ width: '100%' }"
                placeholder="请选择"
                @change="changeCollectionNode(item, index)"
              >
                <el-option
                  v-for="(_item, index) in item.collectionNodeList"
                  :key="index"
                  :label="_item.dictLabel"
                  :value="_item.dictValue"
                >
                </el-option>
              </el-select>
            </div>
            <div>
              <p class="label">平台支付时效</p>
              <el-input-number
                class="jzt-input-number jzt-input-number-hidden suffix-day"
                v-model="item.collectionCycle"
                :min="0"
                :max="365"
                :style="{ width: '100%' }"
                placeholder="请输入"
                controls-position="right"
                allow-clear
              >
              </el-input-number>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { ElNotification, ElMessage } from "element-plus";
import { CirclePlusFilled, CircleCloseFilled } from "@element-plus/icons-vue";
import { selectBusinessAllNode, selectNode, batchUpPlan } from "@/api/system/payment";

const nodeList = ref([]);
const form = ref({ remark: "" });
const list = ref([]);
const _editArr = ref([]);

const emit = defineEmits(["update:isOpen", "submitOk", "cancelSelect"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        type: "add", //add edit view
        editArr: []
      };
    }
  }
});
const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

watch(
  () => props.optionInfo.editArr,
  val => {
    console.log("编辑分期收款计划===", val);
    _editArr.value = [...val];

    selectBusinessAllNode({ factoryIdList: _editArr.value.map(item => item.factoryId) }).then(res => {
      if (res.code === 200) {
        nodeList.value = res.data;

        list.value = [
          {
            collectionType: null, //收款类型;使用1,2,3,4来代替几期   n期款项
            businessNode: null, //商家付款节点 1 接单付款 2 生产完成确认 3 已发货 4 入库完成 5 配送完成 6 安装完成
            businessNodeList: nodeList.value, //商家付款节点list
            collectionNode: null, //供应商收款节点 1 接单付款 2 生产完成确认 3 已发货 4 入库完成 5 配送完成 6 安装完成
            collectionNodeList: [], //供应商收款节点list
            collectionScale: null, //收款比例
            collectionCycle: null //转账时间设置
          }
        ];
      }
    });
  },
  { deep: true }
);

watch(
  () => props.isOpen,
  val => {
    if (val) {
    }
  }
);

/**
 * 删除选中要编辑的工厂
 */
const delFactory = obj => {
  emit("cancelSelect", obj);
};

/**
 * 新增付款节点
 */
const addNode = () => {
  if (list.value === undefined) {
    list.value = [];
  }
  //检查当前页面上的计划是否全部否已选择了商家付款节点
  const businessNodeIsEmpty = list.value?.some(obj => !obj.businessNode || !obj.collectionNode);
  if (businessNodeIsEmpty) {
    return ElMessage({
      message: "请完善当前计划的商家付款节点、供应商收款节点",
      type: "error"
    });
  }
  if (list.value.length === 0) {
    list.value.push({
      collectionType: null, //收款类型;使用1,2,3,4来代替几期   n期款项
      businessNode: null, //商家付款节点 1 接单付款 2 生产完成确认 3 已发货 4 入库完成 5 配送完成 6 安装完成
      businessNodeList: nodeList.value, //商家付款节点list
      collectionNode: null, //供应商收款节点 1 接单付款 2 生产完成确认 3 已发货 4 入库完成 5 配送完成 6 安装完成
      collectionNodeList: [], //供应商收款节点list
      collectionScale: null, //收款比例
      collectionCycle: null //转账时间设置
    });
  } else {
    const preNode = list.value[list.value.length - 1];
    list.value.push({
      collectionType: null, //收款类型;使用1,2,3,4来代替几期   n期款项
      businessNode: null, //商家付款节点 1 接单付款 2 生产完成确认 3 已发货 4 入库完成 5 配送完成 6 安装完成
      businessNodeList: nodeList.value.filter(item => Number(item.dictValue) >= Number(preNode.businessNode)), //商家付款节点list
      collectionNode: null, //供应商收款节点 1 接单付款 2 生产完成确认 3 已发货 4 入库完成 5 配送完成 6 安装完成
      collectionNodeList: [], //供应商收款节点list
      collectionScale: null, //收款比例
      collectionCycle: null //转账时间设置
    });
  }
};

/**
 * 删除付款节点
 */
const delNode = (row, rowIndex) => {
  list.value.splice(rowIndex, 1);
};

const getViewNodelist = businessNode => {
  return nodeList.value.filter(item => Number(item.dictValue) >= Number(businessNode));
};

const changeCollectionNode = (row, rowIndex) => {
  if (rowIndex !== 0) {
    if (Number(row.collectionNode) < Number(list.value[rowIndex - 1].collectionNode)) {
      ElMessage({
        message: "当前节点配置错误，请重新选择",
        type: "error"
      });
      row.collectionNode = "";
    }
  }
};

/**
 *
 * @param row 当前收款计划行
 * @param type 当前下拉框的类型 1：商家下拉 2：供应商下拉
 * @param selectVal 下拉框选择的节点值
 */
const getNodeList = (row, index, selectVal, type) => {
  if (type === 1) {
    row.collectionNode = null;

    //删除当前节点后面的所有数据
    list.value.splice(index + 1);

    //如果存在上一个节点，请求接口，获取当当前行的供应商节点的下拉列表
    const lastNodeValue = index === 0 ? "" : list.value[index - 1].collectionNode;
    selectNode({
      type: 1,
      selectId: row.businessNode,
      lastNodeValue: lastNodeValue,
      factoryIdList: _editArr.value.map(item => item.factoryId)
    }).then(res => {
      if (res.code === 200) {
        row.collectionNodeList = res.data;
      }
    });
  }
};

const save = () => {
  let isAllow = true;
  list.value.map(item => {
    if (
      item.businessNode === "" ||
      item.businessNode === null ||
      item.collectionNode === "" ||
      item.collectionNode === null ||
      item.collectionCycle === "" ||
      item.collectionCycle === null ||
      item.collectionScale === "" ||
      item.collectionScale === null
    ) {
      isAllow = false;
    }
  });
  if (!isAllow) {
    ElNotification({
      title: "提示",
      message: "请完善收款关联节点信息！",
      type: "error",
      duration: 1500
    });
    return;
  }

  let amountTotal = 0;
  const arr = list.value.map((item, index) => {
    amountTotal = amountTotal + Number(item.collectionScale);
    return {
      collectionType: index + 1,
      businessNode: item.businessNode,
      collectionScale: item.collectionScale,
      collectionNode: item.collectionNode,
      collectionCycle: item.collectionCycle
    };
  });
  if (amountTotal < 100 || amountTotal > 100) {
    ElNotification({
      title: "提示",
      message: "付款比例总和必须等于100%！",
      type: "error",
      duration: 1500
    });
    return;
  }

  batchUpPlan({
    factoryIdList: _editArr.value.map(item => item.factoryId),
    detailList: arr
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "批量修改成功",
        type: "success"
      });
      emit("submitOk");
      close();
    }
  });
};

const close = () => {
  _isOpen.value = false;
  reset();
};

const reset = () => {
  list.value = [
    {
      collectionType: null, //收款类型;使用1,2,3,4来代替几期   n期款项
      businessNode: null, //商家付款节点 1 接单付款 2 生产完成确认 3 已发货 4 入库完成 5 配送完成 6 安装完成
      businessNodeList: nodeList.value, //商家付款节点list
      collectionNode: null, //供应商收款节点 1 接单付款 2 生产完成确认 3 已发货 4 入库完成 5 配送完成 6 安装完成
      collectionNodeList: [], //供应商收款节点list
      collectionScale: null, //收款比例
      collectionCycle: null //转账时间设置
    }
  ];
};
</script>
<style lang="scss">
h4 {
  margin: 0;
  padding: 0;
}
.paymen-plan-drawer {
  .el-drawer {
    box-shadow: -8px 0px 16px 0px rgba(0, 38, 73, 0.1);
    border-radius: 10px 0px 0px 10px;
  }
  .el-drawer__header > :first-child {
    flex: none !important;
  }
  .el-drawer__header {
    font-size: 18px;
    color: #131414;
    margin-bottom: 0px;
    padding-bottom: 16px;
    border: 1px solid #d8d8d8;
    justify-content: space-between;
    h4 {
      font-weight: normal;
      position: relative;
      padding-left: 14px;
      &::before {
        position: absolute;
        content: "";
        left: 0;
        top: 6px;
        width: 6px;
        height: 6px;
        background-color: #409eff;
        border-radius: 50%;
      }
    }
  }
  .el-drawer__body {
    font-size: 14px;
  }
  .el-drawer__footer {
    text-align: right !important;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 14px 20px;
  }
}
</style>
<style lang="scss" scoped>
P {
  padding: 0;
  margin: 0;
}
:deep(.arco-input-group) {
  & > .arco-input-wrapper:not(:last-child) {
    --color-neutral-3: white;
  }
}
:deep(.arco-input-wrapper.arco-input-focus) {
  --color-bg-2: #f2f3f5;
}
:deep(.arco-input-wrapper) {
  &:hover {
    background-color: #f2f3f5;
    border-color: transparent;
  }
}
.content {
  .info {
    .select-wrap {
      display: grid;
      gap: 14px;
      grid-template-columns: repeat(5, minmax(0, 1fr));
      margin-top: 14px;
      .select-item {
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #eaecf0;
        text-align: center;
        position: relative;
        padding: 10px 10px;
        color: #4e5969;
        :deep(.el-icon) {
          position: absolute;
          right: -5px;
          top: -5px;
        }
      }
    }
  }

  div.title {
    display: block;
    font-size: 18px;
    color: #3d3d3d;
    border-bottom: 1px solid #dcdfe6;
    margin: 32px -20px 0 -20px;
    padding: 0 20px;
    padding-bottom: 14px;
    font-weight: normal;
  }
  .list {
    .list-item {
      border: 1px solid #f0f0f0;
      margin-top: 20px;
      header {
        line-height: 40px;
        background-color: #f0f0f0;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        img:hover {
          cursor: pointer;
        }
      }
      .options-warp {
        display: grid;
        gap: 10px;
        grid-template-columns: 1fr 240px 210px;
        padding: 14px 20px;
        & > div {
          display: grid;
          grid-template-columns: 110px 1fr;
          &:first-of-type {
            grid-template-columns: 110px 110px 1fr;
          }
          &:last-of-type {
            grid-template-columns: 94px 1fr;
          }
          p.label {
            text-align: right;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            color: #4e5969;
            i {
              font-style: normal;
              display: inline-block;
              padding: 4px 4px 0 0;
            }
          }
        }
      }
    }
  }
}
.title {
  display: inline-block;
  color: #131414;
  font-size: 18px;
  span {
    color: #86909c;
    font-size: 14px;
  }
}
.icon {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #409eff;
  margin: 0 10px 4px 0;
}
</style>
